<template>
   <div>
       <div id="container" ref="container"></div>
   </div>
</template>

<script lang='ts'>
   import { computed, getCurrentInstance, ref, watch,onMounted,defineComponent, toRaw } from 'vue';
   import { templateRef } from '@vueuse/core';
   let $THREE = window.THREE;
   export default defineComponent({
       props:{},
       setup(props,context){
            let {ctx}:any = getCurrentInstance();
            const container = templateRef<any>('container');
            const camera = ref<any>(null);
            const renderer = ref<any>(null);
            const mesh = ref<any>(null);
            const scene = ref<any>(new $THREE.Scene());
            //模拟初始化结束
            const initThree =()=>{
                //场景
                console.log('cube init start');
				camera.value = new $THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
				camera.value.position.z = 400;
                let bump = $THREE.ImageUtils.loadTexture('/bump.jpg');
        // mat.bumpMap = bump;
        // mat.bumpScale = 0.2;
				let texture = new $THREE.TextureLoader().load('/crate.gif');
                // texture.bumpMap = bump;
                // texture.bumpScale = 1;
				const geometry = new $THREE.BoxGeometry( 200, 200, 200 );
				let material = new $THREE.MeshBasicMaterial( { map: texture,bumpMap:bump } );
                // material.bumpMap = bump;
                // material.bumpScale = 0.5;
                let _meshobj = new $THREE.Mesh(geometry, material);
				mesh.value = _meshobj;
                ctx.$nextTick(()=>{
                    console.log(scene.value);
                    scene.value.add(toRaw(mesh.value));
                    renderer.value = new $THREE.WebGLRenderer( { antialias: true } );
                    renderer.value.setPixelRatio( window.devicePixelRatio );
                    renderer.value.setSize( window.innerWidth, window.innerHeight );
                    document.body.appendChild( renderer.value.domElement );
                    loop();
                });
            }
            //帧同步重绘
            const loop =()=> {
                if(mesh.value){     
                    mesh.value.rotation.x += 0.005;
                    mesh.value.rotation.y += 0.01;
                    renderer.value.render(toRaw(scene.value), camera.value);
                    requestAnimationFrame(loop);   
                }else{
                    console.log(mesh);
                }
            }

            function onWindowResize() {
                window.history.go(0);
                initThree();
            }
            // 添加window 的resize事件监听
            window.addEventListener('resize',onWindowResize);

            onMounted(()=>{
                initThree();
            })

           return{
               camera,
               renderer
           }
       }
   })
</script>

<style scoped>
</style>
